package com.dragon.utilslibrary.dblib;

import android.database.sqlite.SQLiteDatabase;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class BaseDaoFactory {

    private static SQLiteDatabase sqLiteDatabase;
    //-------------添加-------------
    private static SQLiteDatabase userDatabase;
    /**数据库加密SQLiteDatabase*/
    private static net.sqlcipher.database.SQLiteDatabase sqlcipherDatabase;
    /**数据库加密SQLiteDatabase*/
    private static net.sqlcipher.database.SQLiteDatabase sqlcipherUserDatabase;
    /**与用户无关的helper*/
    private Map<String, BaseDataDao> mapDataHelper= Collections.synchronizedMap(new HashMap<String, BaseDataDao>());
    /**与用户有关的helper*/
    private Map<String, BaseUserDao> mapUserHelper= Collections.synchronizedMap(new HashMap<String, BaseUserDao>());

    private static BaseDaoFactory instance=new BaseDaoFactory();
    private BaseDaoFactory(){}
    /**
     * 获取与用户无关的一些公共dao
     * 登录之前调用
     * @param clazz
     * @param entityClass
     * @return
     */
    public  synchronized  <T extends BaseDataDao<M>,M> T
    getDataHelper(Class<T> clazz, Class<M> entityClass)
    {
        BaseDataDao baseDao=null;
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            if(sqlcipherDatabase == null || !sqlcipherDatabase.isOpen()){
                mapDataHelper.clear();
                sqlcipherDatabase = openDatabase(PrivateDataBaseEnums.databasefile.getDefaultDBFile(), "123456");
            }

        } else {
            if(sqLiteDatabase == null || !sqLiteDatabase.isOpen()){
                mapDataHelper.clear();
                sqLiteDatabase = openDatabase(PrivateDataBaseEnums.databasefile.getDefaultDBFile());
            }
        }
        if(mapDataHelper.get(clazz.getSimpleName())!=null)
        {
        	return (T) mapDataHelper.get(clazz.getSimpleName());
        }
        try {
            baseDao=clazz.newInstance();
            if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
                baseDao.init(entityClass, sqlcipherDatabase);
            } else {
                baseDao.init(entityClass, sqLiteDatabase);
            }
            mapDataHelper.put(clazz.getSimpleName(),baseDao);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return (T) baseDao;
    }
    /**
     * 获取与用户有关的私有dao
     * 登录成功后调用
     * @param clazz
     * @param entityClass
     * @return
     */
    public  synchronized  <T extends  BaseUserDao<M>,M> T
    getUserHelper(Class<T> clazz, Class<M> entityClass){
        BaseUserDao baseDao=null;
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            if(sqlcipherUserDatabase == null || !sqlcipherUserDatabase.isOpen()){
                mapDataHelper.clear();
                sqlcipherUserDatabase = openDatabase(PrivateDataBaseEnums.databasefile.getUserDBFile(), "123456");
            }

        } else {
            if(userDatabase == null || !userDatabase.isOpen()){
                mapUserHelper.clear();
                userDatabase = openDatabase(PrivateDataBaseEnums.databasefile.getUserDBFile());
            }
        }
        if(mapUserHelper.get(clazz.getSimpleName())!=null)
        {
        	return (T) mapUserHelper.get(clazz.getSimpleName());
        }
        
        try {
            baseDao=clazz.newInstance();
            if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
                baseDao.init(entityClass,sqlcipherUserDatabase);
            } else {
                baseDao.init(entityClass,userDatabase);
            }
            mapUserHelper.put(clazz.getSimpleName(),baseDao);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }

    /***
     * 打开未加密的数据库
     * @param dbPath DB路径
     * @return SQLiteDatabase
     */
    private SQLiteDatabase openDatabase(String dbPath) {
//    	if(!"0".equals(PrivateDataBaseEnums.is_open_sdcard.value)){
//	    	if(dbPath.contains(PrivateDataBaseEnums.logic_db_name.value + ".db")){
////	    		return new DBOpenHelper(AppConfig.mContext, PrivateDataBaseEnums.databasefile.getCurrentUserId().getUser_id()+PrivateDataBaseEnums.logic_db_name.value  + ".db").getWritableDatabase();
//	    		return SQLiteDatabase.openOrCreateDatabase(dbPath,null);
//	    	}else if (dbPath.contains(PrivateDataBaseEnums.user_db_name.value + ".db")) {
//	    		return new DBOpenHelper(AppConfig.mContext, PrivateDataBaseEnums.user_db_name.value  + ".db").getWritableDatabase();
//			}
//    	}
    	return SQLiteDatabase.openOrCreateDatabase(dbPath,null);
    }

    /**
     * 打开加密数据库
     * @param dbPath 数据库路径
     * @param dbPassword 数据库密码
     * @return SQLiteDatabase
     */
    private net.sqlcipher.database.SQLiteDatabase openDatabase(String dbPath, String dbPassword) {
//    	if(!"0".equals(PrivateDataBaseEnums.is_open_sdcard.value)){
//	    	if(dbPath.contains(PrivateDataBaseEnums.logic_db_name.value + ".db")){
////	    		return new DBOpenHelper(AppConfig.mContext, PrivateDataBaseEnums.databasefile.getCurrentUserId().getUser_id()+PrivateDataBaseEnums.logic_db_name.value  + ".db").getWritableDatabase();
//	    		return SQLiteDatabase.openOrCreateDatabase(dbPath,null);
//	    	}else if (dbPath.contains(PrivateDataBaseEnums.user_db_name.value + ".db")) {
//	    		return new DBOpenHelper(AppConfig.mContext, PrivateDataBaseEnums.user_db_name.value  + ".db").getWritableDatabase();
//			}
//    	}
        return net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(dbPath,dbPassword, null);
    }

    /**.
     * 关闭所有db
     */
    public  void closeAllHelper(){
    	closeUserHelper();
    	closeDataHelper();
    }
    /**
     * 关闭用户数据db
     */
    public void closeUserHelper(){
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            if(this.sqlcipherUserDatabase != null){
                this.sqlcipherUserDatabase.close();
                this.sqlcipherUserDatabase = null;
                mapUserHelper.clear();
            }
        } else {
            if(this.userDatabase != null){
                this.userDatabase.close();
                this.userDatabase = null;
                mapUserHelper.clear();
            }
        }
    }
    /**
     * 关闭与用户无关的公共db
     */
    public void closeDataHelper(){
        if ("1".equalsIgnoreCase(DBConfig.encryptionDB)) {
            if(this.sqlcipherDatabase != null){
                this.sqlcipherDatabase.close();
                this.sqlcipherDatabase = null;
                mapDataHelper.clear();
            }
        } else {
            if(this.sqLiteDatabase != null){
                this.sqLiteDatabase.close();
                this.sqLiteDatabase = null;
                mapDataHelper.clear();
            }
        }
//    	if(this.sqLiteDatabase != null){
//    		this.sqLiteDatabase.close();
//    		this.sqLiteDatabase = null;
//            mapDataHelper.clear();
//    	}
    }

    public  static BaseDaoFactory getInstance()
    {
        return instance;
    }

}
